<?php

class User_AdminController extends Ac_AdminController
{

    public function dashboardAction()
    {
        if(!empty($_GET['from']) && !empty($_GET['to']))
		{
			$from = new MongoDate (strtotime($_GET['from']." 00:00:01"));
			$to = new MongoDate (strtotime($_GET['to']." 23:59:59"));
			//echo $from."-".$to;
			
			$this->view->num_active_user = Model_User::all(array('sa' => array('$exists' => false), 'c_dt' => array('$gte' => $from, '$lte' => $to)))->count();
        	$this->view->num_banned_user = Model_User::all(array('sa' => Model_User::STATUS_BANNED, 'c_dt' => array('$gte' => $from, '$lte' => $to)))->count();
			$users = Model_User::all(array('c_dt' => array('$gte' => $from, '$lte' => $to)));
			//language stat
	        $this->view->num_en_user = Model_User::all(array('$or' => array(array('la' => array('$exists' => false)), array('la' => 'en')), 'c_dt' => array('$gte' => $from, '$lte' => $to)))->count();
	        $this->view->num_tc_user = Model_User::all(array('la' => 'tc', 'c_dt' => array('$gte' => $from, '$lte' => $to)))->count();	        
			//newsletter stat
	        $this->view->num_newsletter_subs = Model_User::all(array('nl' => 1, 'c_dt' => array('$gte' => $from, '$lte' => $to)))->count();
	        $this->view->num_newsletter_nonsubs = Model_User::all(array('$or' => array(array('nl' => array('$exists' => false)), array('nl' => '0')), 'c_dt' => array('$gte' => $from, '$lte' => $to)))->count();	        
	        //personal accounts	
	        $this->view->num_personal_account = Model_User::all(array('cid' => array('$exists' => false), 'c_dt' => array('$gte' => $from, '$lte' => $to)))->count();	        
	        //biz accounts	
	        $this->view->num_business_account = Model_User::all(array('cid' => array('$exists' => true), 'c_dt' => array('$gte' => $from, '$lte' => $to)))->count();
	        //user with ads
	        $this->view->num_ad_poster = Model_Listing::distinct('us', array('c_dt' => array('$gte' => $from, '$lte' => $to)));
	        
	        
		}else
		{
			$users = Model_User::all();
			$this->view->num_active_user = Model_User::all(array('sa' => array('$exists' => 0)))->count();
        	$this->view->num_banned_user = Model_User::all(array('sa' => Model_User::STATUS_BANNED))->count();
			//language stat
	        $this->view->num_en_user = Model_User::all(array('$or' => array(array('la' => array('$exists' => false)), array('la' => 'en'))))->count();
	        $this->view->num_tc_user = Model_User::all(array('$or' => array(array('la' => 'tc'))))->count();
	        //newsletter stat
	        $this->view->num_newsletter_subs = Model_User::all(array('nl' => 1))->count();
	        $this->view->num_newsletter_nonsubs = Model_User::all(array('$or' => array(array('nl' => array('$exists' => false)), array('nl' => '0'))))->count();
	        //personal accounts
	        $this->view->num_personal_account = Model_User::all(array('cid' => array('$exists' => false)))->count();
	        //biz accounts	
	        $this->view->num_business_account = Model_User::all(array('cid' => array('$exists' => true)))->count();
	        //user with ads
	        $this->view->num_ad_poster = Model_Listing::distinct('us');
	        
		}
		
        $count = $count2 = 0;
        foreach($users as $user)
		{
			$listing = '';
			$listing = Model_Listing::all(array('us' => $user->_id))->count();
			if($listing == 0)
			{
				$count++;
			}
			
			if($listing >= 100)
			{
				$count2++;
			}
		}
        $this->view->num_non_poster = $count;
        $this->view->num_powerposter = $count2;
        
        
    }

    public function menuAction()
    {
        $this->view->index = $this->_getParam('index');
    }

    public function indexAction() 
    {
        $this->listAction();
    }
    
    public function listAction() 
    {
        $solr = Ac_Search::getClient();

        $_GET['sort'] = $sort = !empty($_GET['sort']) ? $_GET['sort'] : 'recent';
        $page      = !empty($_GET['page']) ? $_GET['page'] : 1;
        $per_page  = 30;
        $query = '';
        if (!empty($_GET['user'])) {
            $query = ' username:'.$_GET['user'].' OR email:'.$_GET['user'];
        }
        else {
            $query = 'status:1 OR status:2';
            if(!empty($_GET['from']) && !empty($_GET['to'])){
				$query .= ' +created_at:['.$_GET['from'].'T00:00:01Z TO '.$_GET['to'].'T23:59:59Z]';
			}
        }
        
        $fields = array();
        $additionalParameters = array();
        
        $this->processRefineSearchForm($page, $per_page, $sort, $query, $fields, $additionalParameters);
        
        $start = ($page-1) * $per_page;
echo $query;
        $list  = $solr->search($query, $start, $per_page, $additionalParameters);

        //$this->view->list    = Model_Listing::all()->limit(50);
        $this->view->list           = $list->response->docs;
        $this->view->listing_number = $list->response->numFound;
        $this->view->page           = $page;
        $this->view->per_page       = $per_page;
		// print_r($list->response->docs);
		// exit;
        $this->render('list');
    }
    
    public function editAction()
    {
        /*
        $key    = $_POST['id'];
        $value  = $_POST['val'];
        $locale = $_POST['loc'];
        Model_Translate::addTranslation($key, $value, $locale);
         * 
         */
        //echo 'ok';exit;
		
		$user = Model_User::find($_GET['id']);
		$company = Model_Company::find(new MongoId($user->cid));
		$this->view->user = $user;  
		$this->view->company = $company; 	


		if($this->_request->isPost()) {
			$user = Model_User::find($_GET['id']);
			$company = Model_Company::find(new MongoId($user->cid));
			if (!empty($_POST['contact_firstname'])) {
                $company->contact_firstname = $_POST['contact_firstname'];
            }
            else  { unset($company->contact_firstname); }
            if (!empty($_POST['contact_lastname'])) {
                $company->contact_lastname = $_POST['contact_lastname'];
            }
            else  { unset($company->contact_lastname); }
			if (!empty($_POST['company_name'])) {
				$num = Model_Company::one(array('username' => $_POST['company_name']));
				if (!empty($num)) {
					$this->view->company_status = 0;	
					$flag = false;
				} else {
					$company->company_name = $_POST['company_name'];
					$company->username = $_POST['company_name'];
				}
            }
			if (!empty($_POST['contact_phone'])) {
                $company->phone = $_POST['contact_phone'];
            }
            else  { unset($company->phone); }
			if (!empty($_POST['business_category'])) {
                $company->business_category = $_POST['business_category'];
            }
			if (!empty($_POST['phone'])) {
                $company->contact_phone = $_POST['phone'];
            }
            else  { unset($company->contact_phone); }
			if (!empty($_POST['website'])) {
                $company->website = ($_POST['website'] == 'http://' || $_POST['website'] == '') ? '' : $_POST['website'];
            }
            else  { unset($company->website); }
			if (!empty($_POST['mailing_address'])) {
                $company->mailing_address = ($_POST['mailing_address'] == 'e.g.: 8 Lucky Building, 88 Caine Road, Central' || $_POST['mailing_address'] == '') ? '' : $_POST['mailing_address'];
            }
            else  { unset($company->mailing_address); }
			if (!empty($_POST['contact_job'])) {
                $company->contact_job = $_POST['contact_job'];
            }
            else  { unset($company->contact_job); }
            if (!empty($_POST['contact_department'])) {
                $company->contact_department = $_POST['contact_department'];
            }
            else  { unset($company->contact_department); }
			if (!empty($_POST['contact_email'])) {
                $company->contact_email = $_POST['contact_email'];
            }
            else  { unset($company->contact_email); }
			if (!empty($_POST['about'])) {
                $company->about = $_POST['about'];
            }
            else  { unset($company->about); }
			if (!empty($_POST['location'])) {
                $company->location = $_POST['location'];
            }
            else  { unset($company->location); }
			
			$company->save();
			$this->_redirect($this->view->geturl('edit','user', null, 'admin1', array('id'=> $_GET['id'])));
		}
		
        $this->render('edit');
    }

    public function displayAction()
    {
    	if(isset($_POST['update']))
		{
			//echo "<pre>";print_r($_POST);echo "</pre>";
			$user = Model_User::find($_POST['id']);
			
			$firstname = $_POST['firstname'];
			$lastname = $_POST['lastname'];
			$display = $_POST['display'];
			$phone = $_POST['phone'];
			$email = $_POST['email'];
			$language = $_POST['language'];
			$notif = $_POST['notif'];
			$about_us = $_POST['about_us'];
			
			if(!empty($firstname))
			{
				$user->fn = $firstname;
			}
			if(!empty($lastname))
			{
				$user->ln = $lastname;
			}
			if(!empty($display))
			{
				$user_test = Model_User::one(array('username' => $display));
				if(empty($user_test))
				{
					$user->un = $display;
				}else
				{
					$this->view->existingdisplay = $display;
				}
			}
			if(!empty($phone))
			{
				$user->ph = $phone;
			}
			if(!empty($email))
			{
				$user_test = Model_User::one(array('email' => $email));
				if(empty($user_test))
				{
					$user->em = $email;
				}else
				{
					$this->view->existingemail = $email;
				}
			}
			if(!empty($language) && $language != "Please Select")
			{
				$user->la = $language;
			}
			if($notif != "Please Select")
			{
				$user->nl = $notif;
			}
			if(!empty($about_us))
			{
				$user->au = $about_us;
			}
			
			$pp = '';
	        $uploads_dir = PUBLIC_PATH.'/images/photo/original/images/profilepic';
	        foreach ($_FILES as $key => $file) {
	            if ($file["error"] == UPLOAD_ERR_OK) {
	                $tmp_name = $file["tmp_name"];
	                $img_name     = $file["name"];
	                //var_dump($tmp_name, $uploads_dir.'/'.$name);
	                move_uploaded_file($tmp_name, $uploads_dir.'/'.$_POST['id']."-".$img_name);
	                if ($key == 'pic') {
	                    $pp = '/images/profilepic/'.$_POST['id']."-".$img_name;
	                    $user->pp = $pp;
	                } 
	            }
	        }   
	        
	        $user->save();
		}
		
		if(isset($_POST['save']))
		{
			$address = $_POST['address'];
			$location = $_POST['location'];
			
			$listings = Model_Listing::all(array('us' => new MongoId($_GET['id'])));
			foreach($listings as $listing)
			{
				if(!empty($location) && $location != "Please Select")
				{
					$listing->ds = new MongoId($location);
				}
				if(!empty($address))
				{
					$listing->st = $address;
				}
				$listing->forceSave();
			}
		}
		
		$user = Model_User::find($_GET['id']);
        $this->view->user = $user;
        $this->render('display');
    }
    
	public function reverseAction()
    {
		$user = Model_User::find($_GET['id']);
		$company = Model_Company::find(new MongoId($user->cid));
		$company->status = Model_Company::STATUS_BANNED;
		$company->save();
		$user->type_account = Model_User::PERSONAL;
		unset($user->cid);
		unset($user->nu);
		$user->save();
		$this->_redirect($this->view->geturl('display','user', null, 'admin1', array('id'=> $_GET['id'])));
		
	}
	
	public function upgradeAction() {

        $user = Model_User::find($_GET['id']);
        $this->view->user = $user;

        if ($this->_request->isPost()) {
            $company = new Model_Company();
            $company->save();
            $cid = $company->_id;
            $flag = true;

            if (!empty($_POST['company_name'])) {
                $company->company_name = $_POST['company_name'];
                $company->username = $_POST['company_name'];
            } else {
                $flag = false;
            }
            if (!empty($_POST['contact_phone'])) {
                $company->phone = $_POST['contact_phone'];
            } else {
                //$flag = false;
            }
            if (!empty($_POST['business_category'])) {
                $company->business_category = $_POST['business_category'];
            } else {
                $flag = false;
            }


            if (!empty($_POST['contact_firstname'])) {
                $company->contact_firstname = $_POST['contact_firstname'];
            } else {
                unset($company->contact_firstname);
            }
            if (!empty($_POST['contact_lastname'])) {
                $company->contact_lastname = $_POST['contact_lastname'];
            } else {
                unset($company->contact_lastname);
            }
            if (!empty($_POST['phone'])) {
                $company->contact_phone = $_POST['phone'];
            } else {
                unset($company->contact_phone);
            }
            if (!empty($_POST['website'])) {
                $company->website = ($_POST['website'] == 'http://' || $_POST['website'] == '') ? '' : $_POST['website'];
            } else {
                unset($company->website);
            }
            if (!empty($_POST['contact_job'])) {
                $company->contact_job = $_POST['contact_job'];
            } else {
                unset($company->contact_job);
            }
            if (!empty($_POST['mailing_address'])) {
                $company->mailing_address = ($_POST['mailing_address'] == 'e.g.: 8 Lucky Building, 88 Caine Road, Central' || $_POST['mailing_address'] == '') ? '' : $_POST['mailing_address'];
            } else {
                unset($company->mailing_address);
            }
            if (!empty($_POST['contact_department'])) {
                $company->contact_department = $_POST['contact_department'];
            } else {
                unset($company->contact_department);
            }
            if (!empty($_POST['contact_email'])) {
                $company->contact_email = $_POST['contact_email'];
            } else {
                unset($company->contact_email);
            }
            if (!empty($_POST['about'])) {
                $company->about = $_POST['about'];
            } else {
                unset($company->about);
            }

            if ($flag == true) {
                $user = Model_User::find($_GET['id']);
                $user->type_account = Model_User::COMPANY_ADMIN;
                $user->cid = new MongoId($cid);
                $user->nu = 1;
                $user->save();
                $company->save();
            }
            $this->_redirect($this->view->geturl('display', 'user', null, 'admin1', array('id' => $_GET['id'])));
        }
        $this->render('upgrade');
    }
	
	
    public function extractDataAction()
    {
        $format = empty($_GET['format']) ? 'csv' : $_GET['format'];
        $start  = strtotime($_GET['start'].' 00:00:00');
        $end    = strtotime($_GET['end'].' 23:59:59');
        
        
        $list = Model_User::all(array('sa' => array('$exists' => 0), 'c_dt' => array('$gt' => new MongoDate($start),
                                                      '$lt' => new MongoDate($end),
                                                      )
        ));

        header('Content-type: text/csv');
        $outstream = fopen("php://output", 'w');
        fputcsv($outstream, array('Date', 'Email', 'Username', 'Samsung Campaign', 'Newsletter'));
        foreach($list as $user) {
            fputcsv($outstream, array(date('Y-m-d H:i:s', $user->created_at), $user->email, $user->username, (int)$user->csg, (int) $user->nl));
        }
        
        fclose($outstream);
        exit;
    }

    public function banAction()
    {
        $user = Model_User::find($_GET['id']);
        
        //Company if present
        if(!empty($user->cid)){
			$company = Model_Company::one(array('_id' => $user->cid));
			if($company){
				$company->status = Model_Company::STATUS_BANNED;
				$company->save();
		        $company->postSave();
			}
		}
        
        $user->status = Model_User::STATUS_BANNED;
        $user->forceSave();

        //Ads 
        $listing = Model_Listing::all(array('us' => new MongoId($_GET['id'])));
        foreach ($listing as $data) {
            if ($data->status == Model_Listing::STATUS_PUBLISHED) {
                $data->status = Model_Listing::STATUS_PUBLISHED_DELETED;
                $data->save();
            }
        }
        
        $this->_redirect($this->view->geturl('display','user', null, 'admin1', array('id'=> $_GET['id'])));
    }

    public function activateAction()
    {
        //User
        $user = Model_User::find($_GET['id']);
        $user->status = Model_User::STATUS_ACTIVE;
        $user->forceSave();
        
        //Company if present
        if(!empty($user->cid)){
			$company = Model_Company::one(array('_id' => $user->cid));
			if($company){
				$company->status = Model_Company::STATUS_ACTIVE;
				$company->save();
		        $company->postSave();
			}
		}
        
        //Ads
        $listing = Model_Listing::all(array('us' => new MongoId($_GET['id'])));
        foreach ($listing as $data) {
            if ($data->status == Model_Listing::STATUS_PUBLISHED_DELETED) {
                $data->status = Model_Listing::STATUS_PUBLISHED;
                $data->save();
            }
        }
        $this->_redirect($this->view->geturl('display','user', null, 'admin1', array('id'=> $_GET['id'])));
    }

    public function deleteAction()
    {
        //User
        $user = Model_User::find($_GET['id']);
        
        //Company if present
        if(!empty($user->cid) && $user->rl == Model_User::COMPANY_ADMIN){
			$company = Model_Company::one(array('_id' => $user->cid));
			if($company){
				$company->deleteCompany();
			}
		}
        
        $user->deleteUser();

        //Ads 
        $listing = Model_Listing::all(array('us' => new MongoId($_GET['id'])));
        foreach ($listing as $data) {
            if ($data->status == Model_Listing::STATUS_PUBLISHED) {
                $data->status = Model_Listing::STATUS_PUBLISHED_DELETED;
                $data->save();
            }
        }
        
        //delete the user from database
        if(!empty($_GET['deldb'])){
			Model_User::remove(array('_id'=> new MongoId($_GET['id'])));
			$this->listAction();
		}
        
        $this->_redirect($this->view->geturl('list','user', null, 'admin1', array('page'=> (empty($_GET['bp'])? "" : $_GET['bp']))));
        //$user = Model_User::one(array('_id'=> new MongoId($_GET['id'])));
        //Model_User::remove(array('_id'=> new MongoId($_GET['id'])));
        //echo "<pre>"; print_r($user);echo "</pre>";exit();
    }

    private function processRefineSearchForm($page, $per_page, $sort, &$query, &$fields, &$additionalParameters)
    {
        $results = false;

        $values     = array();
        $valuesplus = array();
        $get     = $_GET;

        if (!empty($_GET['keyword'])) {
            $values['firstname'] = strtolower(trim($_GET['keyword']));
            $values['lastname']       = strtolower(trim($_GET['keyword']));
            $values['username']       = strtolower(trim($_GET['keyword']));
        }

        foreach($values as $k => $val) {
          $values[$k] = ' '.$k.':'.$val.' ';
        }

        if (!empty($values)) {
            $query = implode(' ', $values);
        }

        if (empty($query)) {
            $query = '*:*';
        }

        switch ($_GET['sort']) {
            case 'rel':
                $sort = 'score desc';
                break;
            case 'recent':
                $sort = 'created_at desc';
                break;
            case 'status':
                $sort = 'status desc';
                break;
            case 'email':
                $sort = 'email asc';
                break;
            default:
                $_GET['sort'] = 'recent';
                $sort         = 'created_at desc';
        }

        $additionalParameters = array(
            'fl'   => '*,score',
            'sort' => $sort,
        );

        $fq                     = '';
        $valuesplus             = array();
        $valuesplus[] = ' +type_obj:'.Model_User::TYPE;


        if (!empty($valuesplus)) {
            $fq .= implode(' ', $valuesplus);
        }

        if (!empty($fq)) {
            $additionalParameters['fq'] = $fq;
        }
        
    }
    

    public function resetPasswordAction()
    {
        $id          = $_GET['id'];
        $u           = Model_User::find($id);
        if (!empty($u)) {
            $password    = Model_User::getNewPassword();
            $u->password = Model_User::generatePassword($password);
            $u->save();
            $this->_helper->json(array('result'=>'ok', 'pwd' => $password));
        }
        $this->_helper->json(array('result'=>'nok'));
    }    
    
	public function extractActiveAction()
    {
    	$period = 'ALL TIME';
		if(!empty($_GET['from']) && !empty($_GET['to']))
		{
			$from = new MongoDate (strtotime($_GET['from']." 00:00:01"));
			$to = new MongoDate (strtotime($_GET['to']." 23:59:59"));
			//echo $from."-".$to;
			$period = $_GET['from']. ' - ' .$_GET['to'];
			//USER
			$active_user = Model_User::all(array('sa' => array('$exists' => 0), 'c_dt' => array('$gte' => $from, '$lte' => $to)));
        	
		}else
		{
			//USER
			$active_user = Model_User::all(array('sa' => array('$exists' => 0)));
		}
		
		$arr = array();
		$arr[] = array('Active Users Peport');
		$arr[] = array('Period', $period);
		$arr[] = array('Registration Date', 'Username', 'Account Type', 'Company Name (if any)', 'Registered Emails', 'Language Used', 'No. of Lisitngs', 'No. of Messages Sent', 'Newsletter Subscription');
		foreach($active_user as $user) {
        	$type = 'Personal';
			$num_listing = 0;
			$num_message =0;
			$company_name = '';
        	if(!empty($user->cid)){
				$type = 'Company Admin';
				//$company_name = Model_Company::one(array('_id' => $user->cid));
				$company_name = $user->company->cn;
			}
			$num_listing = Model_Listing::all(array('us' => $user->_id))->count();
			$num_message = Model_Message::all(array('fo.email' => $user->em))->count();
            $arr[] = array((!empty($user->c_dt->sec) ? date('j M Y', $user->c_dt->sec) : ""), (!empty($user->un) ? $user->un : ''), $type, (!empty($company_name) ? $company_name : ' '), $user->em, (!empty($user->la) ? $user->la : 'en'), $num_listing, $num_message, (!empty($user->nl) ? $user->nl : '0') );
        }
		
		$xls = new Ac_Excel('UTF-8');
		$xls->addArray($arr);
		$xls->generateXML('active-user');
		
        exit;
	}
	
	public function extractBannedAction()
    {
    	$period = 'ALL TIME';
		if(!empty($_GET['from']) && !empty($_GET['to']))
		{
			$from = new MongoDate (strtotime($_GET['from']." 00:00:01"));
			$to = new MongoDate (strtotime($_GET['to']." 23:59:59"));
			//echo $from."-".$to;
			$period = $_GET['from']. ' - ' .$_GET['to'];
			//USER
			$banned_user = Model_User::all(array('sa' => Model_User::STATUS_BANNED, 'c_dt' => array('$gte' => $from, '$lte' => $to)));
        	
		}else
		{
			//USER
			$banned_user = Model_User::all(array('sa' => Model_User::STATUS_BANNED));
		}
        
        $content = '<table><tr><th>Banned User Report</th></tr>';
        $content .= '<tr><td>Report Period</td><td>'.$period.'</td></tr>';
        $content .= '<tr>
					<th>Registration Date</th>
					<th>Registered Emails</th></tr>';
		foreach($banned_user as $user)
		{
			$content .= '<tr>
					<td>'.date('j M Y', $user->c_dt->sec).'</td>
					<td>'.$user->em.'</td></tr>';
		}
        
        $content .= "</table>";
		$filename = "BannedUsers.xls";
        header ("Content-type: application/octet-stream");
		header ("Content-Disposition: attachment; filename=".$filename);
        
        echo $content;
        exit;
	}
	
	public function extractMovieAction()
    {
    	$users = Model_Campaign_User::all(array('cid' => 10));
		
        
        $content = '<table><tr><th>Reference: http://hongkong.asiaclassified.com/campaign/common/id/10</th></tr>';
        $content .= '<tr>
					<th>Campaign ID</th>
					<th>Email</th>
					<th>Facebook Name</th>
					<th>Know AC</th></tr>';
		foreach($users as $user)
		{
			$content .= '<tr>
					<td>'.(string)$user->_id.'</td>
					<td>'.$user->em.'</td>
					<td>'.$user->fb_name.'</td>
					<td>'.$user->kac.'</td></tr>';
		}
        
        $content .= "</table>";
		$filename = "Campaign10.xls";
        header ("Content-type: application/octet-stream");
		header ("Content-Disposition: attachment; filename=".$filename);
        
        echo $content;
        exit;
	}
	
	public function extractMovieWithQAction()
    {
    	$users = Model_Campaign_User::all(array('cid' => 6));
		
        
        $content = '<table><tr><th>Reference: http://hongkong.asiaclassified.com/campaign/common/id/6</th></tr>';
        $content .= '<tr>
					<th>Campaign ID</th>
					<th>Email</th>
					<th>Facebook Name</th>
					<th>Answer</th></tr>';
		foreach($users as $user)
		{
			$content .= '<tr>
					<td>'.(string)$user->_id.'</td>
					<td>'.$user->em.'</td>
					<td>'.$user->fb_name.'</td>
					<td>'.$user->q1.'</td></tr>';
		}
        
        $content .= "</table>";
		$filename = "Campaign10withQ.xls";
        header ("Content-type: application/octet-stream");
		header ("Content-Disposition: attachment; filename=".$filename);
        
        echo $content;
        exit;
	}
}